package com.example.fixsys.controller;

import com.example.fixsys.common.Result;
import com.example.fixsys.entity.Device;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController("device")
public class DeviceController {
    @Resource
    private JdbcTemplate jdbcTemplate;
    @GetMapping("/getDevice")
    public Result<?> GetDevice(){
        String sql = "select * from device";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return Result.success(list);
    }
    @PutMapping("/addDevice")
    public Result<?> AddDevice(@RequestBody Device device){
        String sql="insert into device(deviceNo,deviceKind,deviceName,deviceAddress) VALUES (?,?,?,?)";
        try{
            jdbcTemplate.update(sql, new Object[]{device.getDeviceNo(),device.getDeviceKind(),device.getDeviceName(),device.getDeviceAddress()});
        }catch(Exception e){
            return Result.error("12138","项目已存在");
        }
        return Result.success();
    }

    @PostMapping("/updateDevice")
    public Result<?> UpdateDevice(@RequestBody Device device){
        String sql="update device set deviceKind=?,deviceName=?,deviceAddress=? where deviceNo=?";
        try{
            jdbcTemplate.update(sql, new Object[]{device.getDeviceKind(),device.getDeviceName(),device.getDeviceAddress(),device.getDeviceNo()});
        }catch (Exception e){
            return Result.error("12138","项目不存在");
        }
        return Result.success();
    }

    @DeleteMapping("/deleteDevice")
    public Result<?> DeleteDevice(@RequestBody Device device){
        String sql="delete from device where deviceNo=?";
        try{
            jdbcTemplate.update(sql, new Object[]{device.getDeviceNo()});
        }catch (Exception e){
            return Result.error("12138","项目不存在");
        }
        return Result.success();
    }

    @GetMapping("/recognitionDevice")
    public Result<?> RecognitionDevice(@RequestParam Integer deviceNo){
        String sql = "select deviceName,deviceKind,deviceAddress from device where deviceNo=?";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,new Object[]{deviceNo});
        return Result.success(list);
    }

    @GetMapping("/gainQRCode")
    public Result<?> GainQRCode(@RequestParam Integer deviceNo){
        String sql = "select deviceQRCode from device where deviceNo=?";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,new Object[]{deviceNo});
        return Result.success(list);
    }
}
